package com.ajaxw.main;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

public class RenRen {
	class Ren {
		private String id;
		private boolean vip;
		private boolean selected;
		private boolean mo;
		private String name;
		private String head;
		private ArrayList<String> groups;

		public Ren(String id, boolean vip, boolean selected, boolean mo,
				String name, String head, ArrayList<String> groups) {
			this.id = id;
			this.vip = vip;
			this.selected = selected;
			this.mo = mo;
			this.name = name;
			this.head = head;
			this.groups = groups;
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public boolean isVip() {
			return vip;
		}

		public void setVip(boolean vip) {
			this.vip = vip;
		}

		public boolean isSelected() {
			return selected;
		}

		public void setSelected(boolean selected) {
			this.selected = selected;
		}

		public boolean isMo() {
			return mo;
		}

		public void setMo(boolean mo) {
			this.mo = mo;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getHead() {
			return head;
		}

		public void setHead(String head) {
			this.head = head;
		}

		public ArrayList<String> getGroups() {
			return groups;
		}

		public void setGroups(ArrayList<String> groups) {
			this.groups = groups;
		}
	}

	public RenRen() {
		CookieManager cm = new CookieManager();
		CookieHandler.setDefault(cm);
		HttpURLConnection.setFollowRedirects(true);
	}

	public boolean login(String email, String password) throws IOException {
		URL url = new URL("http://www.renren.com/PLogin.do");
		HttpURLConnection hconn = (HttpURLConnection) url.openConnection();

		int timeout = 30000;
		hconn.setConnectTimeout(timeout);
		hconn.setReadTimeout(timeout);
		hconn.setDoOutput(true);
		hconn.connect();

		String en = "UTF-8";
		String posturl = "http://www.renren.com/SysHome.do";
		String domain = "renren.com";

		String data = "";
		data += "email=" + URLEncoder.encode(email, en);
		data += "&password=" + URLEncoder.encode(password, en);
		data += "&origURL=" + URLEncoder.encode(posturl, en);
		data += "&domain=" + URLEncoder.encode(domain, en);

		hconn.getOutputStream().write(data.getBytes());
		hconn.getOutputStream().flush();

		InputStream inp = hconn.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int b = -1;
		while (-1 != (b = inp.read()))
			baos.write((byte) b);

		String str = new String(baos.toByteArray(), "utf-8");
		if (str.indexOf("\u9000\u51FA") != -1)
			return true;
		else
			return false;
	}

	public String getStatus(String id) throws MalformedURLException,
			IOException {
		String url = "http://www.renren.com/profile.do"
				+ "?portal=homeFootprint&ref=home_footprint&id=" + id;

		HttpURLConnection hconn = (HttpURLConnection) (new URL(url))
				.openConnection();

		int timeout = 30000;
		hconn.setConnectTimeout(timeout);
		hconn.setReadTimeout(timeout);
		hconn.connect();

		InputStream inp = hconn.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int b = -1;
		while (-1 != (b = inp.read()))
			baos.write((byte) b);
		String str = new String(baos.toByteArray(), "utf-8");

		String status = "";
		Document doc = Jsoup.parse(str);
		Elements links = doc.select("span#currentStatus");
		if (!links.isEmpty()) {
			List<Node> nodes = links.get(0).childNodes();

			for (Node node : nodes) {
				if (node.nodeName().equalsIgnoreCase("img")
						&& node.hasAttr("alt")) {
					status += "(" + node.attr("alt") + ")";
				} else if (node.nodeName().equalsIgnoreCase("#text"))
					status += node.toString();
				else
					status += "?";
			}
		}

		return status;
	}

	private String getFriendsJsonString() throws MalformedURLException,
			IOException {
		String url = "http://friend.renren.com/myfriendlistx.do";
		String str = this.get(url);

		Pattern p = Pattern.compile("var[ ]+friends=(\\[[^;]+?\\]);");
		Matcher m = p.matcher(str);

		if (m.find()) {
			str = m.group(1);
		} else {
			str = null;
		}

		return str;
	}

	public ArrayList<Ren> getFriends() throws JSONException,
			MalformedURLException, IOException {
		String str = this.getFriendsJsonString();
		if (str == null)
			str = "[]";

		ArrayList<Ren> friends = new ArrayList<Ren>();
		friends.clear();

		JSONObject jsonObj = new JSONObject("{friends:" + str + "}");
		JSONArray jsonArr = jsonObj.getJSONArray("friends");

		int numFriends = jsonArr.length();
		for (int j = 0; j < numFriends; j++) {
			JSONObject jo = jsonArr.getJSONObject(j);
			String id = jo.getString("id");
			boolean vip = jo.getBoolean("vip");
			boolean selected = jo.getBoolean("selected");
			boolean mo = jo.getBoolean("mo");
			String name = jo.getString("name");
			String head = jo.getString("head");
			ArrayList<String> groups = new ArrayList<String>();
			groups.clear();

			JSONArray arr = jo.getJSONArray("groups");
			for (int i = 0; i < arr.length(); i++) {
				groups.add(arr.getString(i));
			}

			friends.add(new Ren(id, vip, selected, mo, name, head, groups));
		}

		return friends;
	}

	public String get(String url) throws MalformedURLException, IOException {
		HttpURLConnection hconn = (HttpURLConnection) (new URL(url))
				.openConnection();

		int timeout = 30000;
		hconn.setConnectTimeout(timeout);
		hconn.setReadTimeout(timeout);
		hconn.connect();

		InputStream inp = hconn.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int b = -1;
		while (-1 != (b = inp.read()))
			baos.write((byte) b);
		String str = new String(baos.toByteArray(), "utf-8");

		return str;
	}
}
